import json
from datetime import datetime, timedelta

from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

# Create your views here.
from .models import *
import jwt
def empty(c):
    return c is None or str(c).strip()==''
# 登录接口-验证通过后，根据用户名、密码使用PyJWT签发token返回前端
@csrf_exempt
def login(request):
    if request.method=='POST':
        data=json.loads(request.body)
        username=data.get('username')
        password=data.get('password')
        if empty(username) or empty(password):
            return JsonResponse({'msg':'用户名或密码不能为空'},status=401)
        if user.objects.filter(username=username).exists()==False:
            return JsonResponse({'msg': '用户名不存在'}, status=401)
        yh=user.objects.get(username=username)
        if password!=password:
            return JsonResponse({'msg': '密码错误'}, status=401)
        py={'yh':yh.id}
        mi='123456'
        token=jwt.encode(py,mi)
        return JsonResponse({
            'msg':'登录成功',
            'token':token
        })

# ②部门查询接口
def get_department(request):
    data=department.objects.all()
    list=[]
    for i in data:
        list.append(model_to_dict(i))
    return JsonResponse({
        'msg':'部门查询成功',
        'data':list
    })
# ③员工CRUD接口、离职接口‌（多表关联）
# 离职前校验考勤记录
# 分页和条件查询
@csrf_exempt
def getlist(request):
    if request.method=='GET':
        data=work.objects.all()
        total=len(data)
        name=request.GET.get('name')
        # 分页查询
        page=request.GET.get('page',1)
        size=request.GET.get('size') or 10
        if name:
            data=data.filter(name__contains=name)
        data=Paginator(data,size).get_page(page)
        list=[]
        for i in data:
            list.append(model_to_dict(i))
        return JsonResponse({
            'msg': '分页查询成功',
            'data': list,
            'total':total
        })
    elif request.method=='POST':
        data=json.loads(request.body)
        add=work.objects.create(
            name=data['name'],
            depment_id=data['depment_id'],
            money=data['money'],
            workid=data.get('workid'),
            state=data['state']
        )
        return JsonResponse({
            'msg':'添加成功',
            'data':model_to_dict(add)
        })
# 离职前校验考勤记录
@csrf_exempt
def update_delete(request):
    if request.method=='PUT':
        data=json.loads(request.body)
        id=data.get('id')
        xg=work.objects.get(id=id)
        xg.name=data['name'],
        xg.depment_id=data.get('depment_id'),
        xg.money=data.get('money'),
        xg.workid=data.get('workid'),
        xg.state=data.get('state')
        xg.save()
        return JsonResponse({'msg':'修改成功','data':model_to_dict(xg)})
    elif request.method=='DELETE':
        data=json.loads(request.body)
        id=data.get('id')
        work.delete(id)
        return JsonResponse({'msg':'删除成功'})

# ④考勤记录接口‌（多表关联）
@csrf_exempt
def kq(request):
    if request.method=='GET':
        data=work.objects.all()
        workid_id=request.GET.get('workid_id')
        # 分页查询
        page=request.GET.get('page',1)
        size=request.GET.get('size') or 10
        if workid_id:
            data=data.filter(workid_id=workid_id)
        data=Paginator(data,size).get_page(page)
        list=[]
        for i in data:
            list.append(model_to_dict(i))
        return JsonResponse({
            'msg': '考勤分页查询成功',
            'data': list
        })
    elif request.method=='POST':
        data=json.loads(request.body)
        add=kq.objects.create(
            wokid_id=data['workid_id'],
            date=datetime.now()+timedelta(days=30),
            type=data['type'],
            eg=data['eg']
        )
        return JsonResponse({
            'msg':'添加成功',
            'data':model_to_dict(add)
        })